package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	businessReq "github.com/flipped-aurora/gin-vue-admin/server/model/business/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type OptionService struct {
}

// CreateOption 创建选项内容记录
// Author [piexlmax](https://github.com/piexlmax)
func (optionService *OptionService) CreateOption(option *business.Option) (err error) {
	err = global.GVA_DB.Create(option).Error
	return err
}

// CreateOptions 创建选项内容记录
// Author [piexlmax](https://github.com/piexlmax)
func (optionService *OptionService) CreateOptions(optionList []*business.Option) (err error) {
	err = global.GVA_DB.Create(optionList).Error
	return err
}

// DeleteOption 删除选项内容记录
// Author [piexlmax](https://github.com/piexlmax)
func (optionService *OptionService) DeleteOption(option business.Option) (err error) {
	err = global.GVA_DB.Delete(&option).Error
	return err
}

// DeleteOptionByIds 批量删除选项内容记录
// Author [piexlmax](https://github.com/piexlmax)
func (optionService *OptionService) DeleteOptionByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]business.Option{}, "id in (?)", ids.Ids).Error
	return err
}

// UpdateOption 更新选项内容记录
// Author [piexlmax](https://github.com/piexlmax)
func (optionService *OptionService) UpdateOption(option business.Option) (err error) {
	err = global.GVA_DB.Save(&option).Error
	return err
}

// GetOption 根据id获取选项内容记录
// Author [piexlmax](https://github.com/piexlmax)
func (optionService *OptionService) GetOption(id uint) (option business.Option, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&option).Error
	return
}

// GetOptionInfoList 分页获取选项内容记录
// Author [piexlmax](https://github.com/piexlmax)
func (optionService *OptionService) GetOptionInfoList(info businessReq.OptionSearch) (list []business.Option, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&business.Option{})
	var options []business.Option
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.QuestionnaireUuid != "" {
		db = db.Where("questionnaire_uuid = ?", info.QuestionnaireUuid)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&options).Error
	return options, total, err
}

// GetOptionInfoListByQuestionnaire 分页获取选项内容记录
func (optionService *OptionService) GetOptionInfoListByQuestionnaire(questionnaireUuid string) (list []business.Option, err error) {
	// 创建db
	db := global.GVA_DB.Model(&business.Option{})
	var options []business.Option

	db = db.Where("questionnaire_uuid = ?", questionnaireUuid)

	err = db.Find(&options).Error
	return options, err
}
